<template>
  <div id="checkTabels" ref="checkTabels">
    <div class="top1">
      <el-collapse v-model="collapse">
        <el-collapse-item name="1" :disabled="countData.errMsg == false">
          <template slot="title">
            <div class="errTitle">
              <div>
                共导入<span class="Total">{{ countData.allCount }}</span
                >笔数据,其中 <span class="errorCount">{{ countData.errCount }}</span
                >笔数据存在错误信息;
              </div>
              <div>查看错误信息</div>
            </div>
          </template>
          <div>
            <template v-for="(item, index) in countData.errMsg">
              <el-tag type="info" style="margin: 3px 3px" v-if="item" :key="item + index">{{ item }}</el-tag>
            </template>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <div class="top2">
      <div class="left">
        <span :class="area3_tab == 1 ? 'btn btn_hover' : 'btn'" @click="area3_tab = 1">错误信息</span>
        <span>|</span>
        <span :class="area3_tab == 2 ? 'btn btn_hover' : 'btn'" @click="area3_tab = 2">全部信息</span>
      </div>
      <div class="right" v-if="area3_tab == 1">
        <el-button type="primary" @click="reVerify" :loading="loadingInstance.visible">重新验证</el-button>
        <el-button type="default" @click="exportInfo" :loading="loadingInstance.visible">导出错误信息</el-button>
      </div>
    </div>
    <div class="top3">
      <div style="width: 100%; height: 95%">
        <template>
          <ux-grid border show-overflow ref="plxTable" :height="table_height" keep-source :data="area3_tab == 2 ? selectTable.rows : selectTable.error_rows" :highlightCurrentRow="false" :edit-config="{ trigger: 'click', mode: 'cell' }">
            <!-- <ux-table-column type="checkbox" width="60"></ux-table-column> -->
            <!--autofocus，如果是自定义渲染可以指定聚焦的选择器，他的作用很明显就是你点击一下就帮你去获取焦点。
              你无需点击第二次再去获取焦点。autofocus的值就是你编辑型输入框（edit）组件的类名-->
            <ux-table-column v-for="(item, index) in area3_tab == 2 ? selectTable.columns : selectTable.error_columns" :field="item.columnid" :title="item.columnname" min-width="160" :edit-render="area3_tab == 1 ? { autofocus: '.el-input__inner' } : false" :key="item.columnid + index">
              <template v-slot:edit="scope">
                <!-- <div :class="scope.row.ErrorCells">错误错误</div> -->
                <!--  -->
                <!--autofocus绑定的类名就是这个组件的class类名。帮助获取输入框焦点-->
                <!-- <el-input v-model="scope.row.name"></el-input> -->
                <cellContent :item="item" :tempRow="scope.row" :key="item.columnid + scope.row._XID + '1'" :subcompanyDepOptions="item.datatype == 7 ? area3Data.subcompanyDepOptions : []"></cellContent>
              </template>
              <!--写非编辑状态下的样式, 看最底部的style样式部分吧 有写my-input-sc样式哦-->
              <template v-slot="scope">
                <!-- <div :class="scope.row.ErrorCells">错误错误</div> -->
                <!-- <span class="my-input-sc">{{ scope.row[item.columnid] }}</span> -->
                <cellContentText :item="item" :tempRow="scope.row" :key="item.columnid + scope.row._XID + '2'" :subcompanyDepOptions="item.datatype == 7 ? area3Data.subcompanyDepOptions : []"></cellContentText>
              </template>
            </ux-table-column>
          </ux-grid>
        </template>
      </div>
      <!-- <el-tabs v-model="activeName" tab-position="bottom" type="border-card" @tab-click="changeTable">
        <el-tab-pane :label="item.tableName" :name="item.tableName" :key="item.tableName" v-for="item in area3Data.tables"></el-tab-pane>
      </el-tabs> -->
    </div>
  </div>
</template>
<script>
import { UxGrid, UxTableColumn } from "umy-ui";
import cellContent from "../editEmployee/cell.vue";
import cellContentText from "../editEmployee/cellText.vue";
import { Loading } from "element-ui";
export default {
  name: "checkTabels",
  components: {
    UxGrid,
    UxTableColumn,
    cellContent,
    cellContentText,
  },
  data() {
    return {
      collapse: [],
      //area3页面已选中表格
      selectTable: {
        rows: [],
        columns: [],
      },
      //area3全部数据
      area3Data: {},
      //area3 全部信息|错误信息
      area3_tab: 1,
      isreloadTable: false,
      countData: {
        errCount: 0,
        allCount: 0,
        errMsg: "",
      },
      //loding实例
      loadingInstance: {
        visible: false,
      },
      activeName: "",
      selectColumn: {},
      table_height: 0,
    };
  },
  props: {
    //系统字段
    systemAttribute: {
      type: Array,
    },
    //Excel字段
    attributes: {
      type: Array,
    },
    resData: {
      type: Object,
      default: null,
    },
    isEdit: {
      type: Boolean,
    },
    fileCacheKey: {
      type: String,
    },
    rowIndex: {
      type: Number,
      default: 1,
    },
    moduleCode: {
      type: Number,
      default: 0,
    },
  },
  watch: {
    collapse(newData) {
      if (newData && newData.length > 0) {
        this.changeHeight(170);
      } else {
        this.changeHeight(70);
      }
    },
    watchByLoad(newData) {
      this.getData();
    },
    selectTable: {
      handler(newData) {
        newData.error_rows.map((m) => {
          this.selectTable.rows[m.rowIndex] = m;
        });
      },
      deep: true,
    },
  },
  computed: {
    columnClassName() {
      return (columnId, rowId) => {
        if (columnId == this.selectColumn.columnid && rowId == this.selectColumn.rowId) {
          return "actviceColumn";
        }
      };
    },
    watchByLoad() {
      const { attributes, systemAttribute } = this;
      return {
        attributes,
        systemAttribute,
      };
    },
  },
  mounted() {
    window.addEventListener("resize", this.changeHeight(70));
  },
  methods: {
    getData() {
      if (this.resData.excelDataset) {
        this.area3Data = this.resData.excelDataset;
        this.area3Data.tables.forEach((table) => {
          table.error_columns = JSON.parse(JSON.stringify(table.columns));
          table.error_rows = [];
          for (let rowIndex = 0; rowIndex < table.rows.length; rowIndex++) {
            if (table.rows[rowIndex]["ErrorCells"]) {
              let errCell = {
                columnid: "ErrorMsg",
                columnname: "错误信息",
                datatype: -1,
                isRequired: false,
                maxLength: 0,
              };
              //添加错误列
              table.error_columns.splice(0, 0, errCell);
              //添加错误行并删除原有内容
              table.error_rows.push(table.rows[rowIndex]);
            }
          }
        });
        this.isreloadTable = true;
        this.findCount(this.area3Data.tables);
        //默认选择第一个表格
        this.changeTable({ index: 0 });
        this.$emit("closeLoading");
      } else {
        this.getTables();
      }
    },
    changeHeight(h) {
      this.table_height = this.$refs.checkTabels.clientHeight - h - 40 - 50;
      this.$refs.plxTable.doLayout(true);
    },
    setClick(obj) {
      this.selectColumn = obj;
    },
    //确认导入数据
    ConfirmImportData() {
      let data = [];
      this.area3Data.tables.forEach((item) => {
        let table = {};
        table.tableName = item.tableName;
        table.rows = [];
        item.rows.forEach((rowItem) => {
          let row = { cells: [] };
          let keys = Object.keys(rowItem);
          keys.forEach((key) => {
            if (key != "ErrorCells" && key != "ErrorMsg" && key != "_XID" && key != "ErrorDetails" && key != "rowIndex") {
              row.cells.push({
                key: key,
                value: rowItem[key],
              });
            }
          });
          table.rows.push(row);
        });
        data.push(table);
      });
      return data;
    },
    //下载错误信息
    async exportInfo() {
      this.loadingInstance = Loading.service({ fullscreen: false, target: document.getElementById("ImportEmployeeNew") });
      let datas = [];
      this.area3Data.tables.forEach((item) => {
        let table = {};
        table.tableName = item.tableName;
        table.rows = [];
        item.rows.forEach((rowItem) => {
          let row = { cells: [] };
          let keys = Object.keys(rowItem);
          keys.forEach((key) => {
            if (key != "ErrorCells" && key != "ErrorMsg" && key != "ErrorDetails" && key != "rowIndex" && key != "_XID") {
              row.cells.push({
                key: key,
                value: rowItem[key],
              });
            }
          });
          table.rows.push(row);
        });
        datas.push(table);
      });
      const { data } = await this.$api.importUser.ExportErrorData({ isEdit: this.isEdit, moduleCode: this.moduleCode, data: datas });
      const download = ({ data, fileName }) => {
        const blob = new Blob([data], { type: "application/vnd.ms-excel" });
        const blobUrl = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = blobUrl;
        a.download = `${fileName}.xlsx`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(blobUrl);
        this.loadingInstance.close();
      };
      download({ data, fileName: "错误信息" });
    },
    //重新验证
    reVerify() {
      this.loadingInstance = Loading.service({ fullscreen: false, target: document.getElementById("ImportEmployeeNew") });
      let data = [];
      this.area3Data.tables.forEach((item) => {
        let table = {};
        table.tableName = item.tableName;
        table.rows = [];
        item.error_rows.forEach((errorRowItme) => {
          item.rows[errorRowItme.rowIndex] = errorRowItme;
        });
        item.rows.forEach((rowItem) => {
          let row = { cells: [] };
          let keys = Object.keys(rowItem);
          keys.forEach((key) => {
            if (key != "ErrorCells" && key != "ErrorMsg" && key != "_XID" && key != "rowIndex" && key != "ErrorDetails") {
              row.cells.push({
                key: key,
                value: rowItem[key],
              });
            }
          });
          table.rows.push(row);
        });
        data.push(table);
      });
      this.$api.importUser
        .RepetitionCheckExcel({ isEdit: this.isEdit, moduleCode: this.moduleCode, data: data })
        .then((res) => {
          this.loadingInstance.close();
          this.area3Data = res.data.data;
          this.area3Data.tables.forEach((table) => {
            table.error_columns = JSON.parse(JSON.stringify(table.columns));
            table.error_rows = [];
            for (let rowIndex = 0; rowIndex < table.rows.length; rowIndex++) {
              if (table.rows[rowIndex]["ErrorCells"] && table.rows[rowIndex]["ErrorMsg"]) {
                if (!table.error_columns.find((m) => m.columnid == "ErrorMsg")) {
                  let errCell = {
                    columnid: "ErrorMsg",
                    columnname: "错误信息",
                    datatype: -1,
                    isRequired: false,
                    maxLength: 0,
                  };
                  //添加错误列
                  table.error_columns.splice(0, 0, errCell);
                }
                //添加错误行并删除原有内容
                table.error_rows.push({ ...table.rows[rowIndex], rowIndex: rowIndex });
              }
            }
          });
          this.findCount(this.area3Data.tables);
          // console.log("changeTable");
          this.$nextTick(() => {
            //默认选择第一个表格
            // console.log(this.area3Data, "this.area3Data");
            this.changeTable({ index: 0, name: this.area3Data.tables[0].tableName });
          });
        })
        .catch(() => {
          this.loadingInstance.close();
        });
    },
    // 获取单元格className
    changeTd(columnId) {
      let className = "";
      if (this.area3_tab == 2) {
        className += "";
      } else {
        if (this.selectTable.rows.find((m) => m["ErrorCells"]?.indexOf(columnId) > -1)) {
          className += " error";
        }
      }
      return className;
    },
    //area3 改变tab事件  sheet表(表格)改变事件
    changeTable(obj) {
      if (obj.name) {
        this.activeName = obj.name;
      }
      // console.log("进入changeTable");
      var selectTable = this.area3Data.tables[obj.index];
      let rules = {};
      selectTable.columns.forEach((item) => {
        rules[item.columnid] = [{ require: item.isRequired, message: `请填写${item.columnname}` }];
      });
      this.selectTable = {
        columns: selectTable.columns,
        rows: selectTable.rows,
        error_columns: selectTable.error_columns,
        error_rows: selectTable.error_rows,
        rules: rules,
      };
      //使用v-if刷新组件
      this.isreloadTable = false;
      this.isreloadTable = true;
      //this.$refs.plxTable.reloadColumn(this.area3_tab == 2 ? selectTable.columns : selectTable.error_columns);
      this.$refs.plxTable.reloadData(this.area3_tab == 2 ? selectTable.rows : selectTable.error_rows);
      this.$refs.plxTable.doLayout();
    },
    //查找统计数量和错误信息
    findCount(tables) {
      let allCount = 0;
      let errCount = 0;
      let errMsg = [];
      tables.forEach((table) => {
        allCount += table.rows?.length ?? 0;
        if (table.error_rows?.length > 0) {
          errCount += table.error_rows?.length ?? 0;
          table.error_rows.forEach((row) => {
            errMsg.push(row.ErrorMsg);
          });
        }
      });
      if (errCount <= 0) {
        this.area3_tab = 2;
      }
      this.countData = {
        allCount,
        errCount,
        errMsg,
      };
      // console.log(tables, "findCount", this.countData);
    },
    async getTables() {
      var systemAttribute = [];
      this.systemAttribute.map((m) => systemAttribute.push(...m.Columns));
      var Parameter = [];
      this.attributes.forEach((element) => {
        var excelColumn = element.isRequire ? "*" + element.name : element.name;
        var systemColumn = systemAttribute.find((m) => element.systemAttribute == m.id)?.name;
        Parameter.push({ excelColumn, systemColumn });
      });
      let data = { fileCacheKey: this.fileCacheKey, isEdit: this.isEdit, moduleCode: this.moduleCode, data: { columns: Parameter, titleRowIndex: this.rowIndex } };
      await this.$api.importUser
        .CheckExcel(data)
        .then((res) => {
          if (res.data.status == 200) {
            this.area3Data = res.data.data;
            if (this.area3Data.tables && this.area3Data.tables?.length > 0) {
              this.area3Data.tables.forEach((table) => {
                table.error_columns = JSON.parse(JSON.stringify(table.columns));
                table.error_rows = [];
                for (let rowIndex = 0; rowIndex < table.rows.length; rowIndex++) {
                  if (table.rows[rowIndex]["ErrorCells"]) {
                    if (!table.error_columns.find((m) => m.columnid == "ErrorMsg")) {
                      let errCell = {
                        columnid: "ErrorMsg",
                        columnname: "错误信息",
                        datatype: -1,
                        isRequired: false,
                        maxLength: 0,
                      };
                      //添加错误列
                      table.error_columns.splice(0, 0, errCell);
                    }
                    //添加错误行
                    table.error_rows.push({ ...table.rows[rowIndex], rowIndex: rowIndex });
                  }
                }
              });

              this.findCount(this.area3Data.tables);
              // console.log(this.area3Data, "this.area3Data");
              //默认选择第一个表格
              this.changeTable({ index: 0, name: this.area3Data.tables[0]?.tableName });
              // this.active++;

              this.table_height = this.$refs.checkTabels.clientHeight - 70 - 40 - 50;
              this.$refs.plxTable.doLayout(true);
            }
          } else {
            this.$emit("activeChange", 1);
            this.$emit("closeLoading");
          }
        })
        .catch((res) => {
          console.log(res);
          this.$emit("activeChange", 1);
        });
      this.$emit("closeLoading");
    },
  },
};
</script>
<style lang="less" scoped>
#checkTabels {
  width: 100%;
  height: 100%;
  // display: flex;
  // flex-flow: column;
  // align-items: flex-start;
  padding-top: 24px;
  // justify-content: space-between;
  padding-bottom: 60px;
  .top1 {
    width: 100%;
    max-height: 150px;
    margin-bottom: 30px;
    overflow: hidden;
    .Total {
      font-size: 18px;
      color: #47a5e9;
    }
    .errorCount {
      font-size: 18px;
      color: #ff5e67;
    }
    .errTitle {
      display: flex;
      flex-flow: row;
      justify-content: space-between;
      width: 100%;
      padding: 5px;
    }
    :deep(.el-collapse) {
      .el-collapse-item__wrap {
        height: 100px;
        overflow: auto;
      }
    }
  }
  .top2 {
    width: 100%;
    margin-bottom: 10px;
    display: flex;
    flex-flow: row;
    justify-content: space-between;
    .left {
      span {
        margin-right: 15px;
      }
      .btn {
        cursor: pointer;
      }
      .btn_hover {
        color: #39a4ed;
      }
    }
  }
  .top3 {
    width: 100%;
    position: relative;
    .my-input-sc {
      display: inline-block;
      height: auto;
      line-height: 30px;
      -webkit-appearance: none;
      background-color: #ffffff;
      background-image: none;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      box-sizing: border-box;
      color: #606266;
      font-size: inherit;
      outline: none;
      padding: 0 15px;
      transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
      width: 100%;
    }
    :deep(.el-tabs) {
      position: absolute;
      .el-tabs__content {
        display: none;
      }
      .is-bottom {
        margin-top: 0 !important;
      }
    }
    :deep(.elx-grid) {
      .elx-table {
        .elx-table--body {
          // .error {
          //   height: 100%;
          //   border: 1px solid red;
          //   line-height: 50px;
          // }
          .eventNone {
            pointer-events: none !important;
          }
          .elx-body--column {
            overflow: hidden;
            .tips {
              color: #999999;
              text-decoration: underline;
            }
          }
          .col--actived {
            background-color: #f4f8fe;
          }
          .elx-body--column {
            .elx-cell {
              height: 100%;
              padding-left: 0;
              padding-right: 0;
            }
          }
        }
      }
    }
  }
}
</style>
